package com.zeus.controller;

import com.zeus.pojo.Admin;
import com.zeus.service.AdminService;
import com.zeus.utils.MD5Utils;
import com.zeus.utils.MapControl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    //    跳转到add.jsp
    @GetMapping("/create")
    public String v_create() {
        return "admin/add";
    }

    //跳转到add.jsp的同时进行验证
    @PostMapping("/create")
    @ResponseBody
    public Map<String, Object> create(@RequestBody Admin admin) {
        admin.setPassword(MD5Utils.getMD5(admin.getPassword()));
        int result = adminService.create(admin);
        if (result <= 0) {
            //失败的情况下
            return MapControl.getInstance().error().getMap();
        }
        return MapControl.getInstance().success().getMap();
    }

    //批量删除方法
    @PostMapping("/delete")
    @ResponseBody
    public Map<String, Object> delete(String ids) {
        int result = adminService.deleteBatch(ids);
        if (result <= 0) {
            //失败的情况下
            return MapControl.getInstance().error().getMap();
        }
        return MapControl.getInstance().success().getMap();
    }

    //    更新操作
    @GetMapping("/detail")
    public String detail(int id, ModelMap modelMap) {
        Admin admin = adminService.detail(id);
        modelMap.addAttribute("admin",admin);
        return "admin/update";
    }

   //update
   @PostMapping("/update")
   @ResponseBody
   public Map<String, Object> update(@RequestBody Admin admin){
       int result = adminService.update(admin);
       if(result<=0){
           //失败的情况下
           return MapControl.getInstance().error().getMap();
       }
       return MapControl.getInstance().success().getMap();
   }

    //跳转到list页面
    @GetMapping("/list")
    public String list() {
        return "admin/list";
    }

    //把管理员的数据显示在大屏上
    @PostMapping("/query")
    @ResponseBody
    public Map<String, Object> query(@RequestBody Admin admin, ModelMap modelMap) {
        System.out.println(admin.getPage());
        System.out.println(admin.getLimit());
        System.out.println(admin.getAccount());
        List<Admin> list = adminService.query(admin);
        Integer count = adminService.count(admin);
        return MapControl.getInstance().page(list, count).getMap();
    }


}
